package com.spring.team_propaganda_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spring.team_propaganda_system.dao.PictureDao;
import com.spring.team_propaganda_system.entity.Picture;
import com.spring.team_propaganda_system.entity.User;
import com.spring.team_propaganda_system.utils.JwtToken;
import com.spring.team_propaganda_system.utils.MyUtil;
import com.spring.team_propaganda_system.utils.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.util.List;
import java.util.UUID;

@CrossOrigin
@Controller
@RequestMapping("/pictureController")
@Api(value = "PictureController", description = "图片相关api")
@Transactional
public class PictureController {
    Boolean flag;
    MyUtil myUtil = new MyUtil();
    @Autowired(required = false)
    PictureDao pictureDao;

    /**
     * 图片上传
     * @param pictureFile
     * @param picture_description
     * @param request
     * @param Authorization
     * @param response
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @ApiOperation("图片上传")
    @PostMapping("/web/AddPicture")
    @ResponseBody
    public ResponseEntity AddPicture(@RequestParam(required = true) MultipartFile pictureFile,
                                                 @RequestParam(required = false) String picture_description,
                                                 HttpServletRequest request,
                                                 @RequestHeader String Authorization,
                                                 HttpServletResponse response) throws IOException, ParseException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*星号表示所有的域都可以接受，*/
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        ResponseEntity responseEntity;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        if (user.getUser_role()!=2){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
            //图片资源访问路径
            String fileLocation = "/static/restaurantRes/";
            //获取提交文件名称
            String filename = pictureFile.getOriginalFilename();
            String newfilename = System.currentTimeMillis() + UUID.randomUUID().toString().replace(".", "").substring(0, 6) + "." + filename.substring(filename.lastIndexOf(".") + 1);

            //定义上传文件存放的路径
            String path = request.getSession().getServletContext().getRealPath(fileLocation);//此处为tomcat下的路径，服务重启路径会变化
            System.out.println(path);
            //返回保存的url，根据url可以进行文件查看或者下载
            String filePath = request.getScheme() + "://" + request.getServerName()
                    + ":" + request.getServerPort() //端口 https443端口无需添加
                    + fileLocation + newfilename;

            String head_portrait = filePath;//根路径+文件名
            File file = new File("/www/javaweb/propaganda_system/picture/" + newfilename);
            Picture picture = new Picture();
            picture.setPicture_path(head_portrait);
            picture.setPicture_description(picture_description);
//            //修改信息
//            pictureDao.updateById(picture);
            pictureDao.insert(picture);
            pictureFile.transferTo(file);
        responseEntity = ResponseEntity.ok();
            Picture picture1=pictureDao.selectById(picture.getPicture_id());
        responseEntity.putDataValue("picture",picture1);
            System.out.println("图片上传成功");
            return responseEntity;
    }

    /**
     * 图片列表
     * @return
     */
    @ApiOperation("图片列表")
    @PostMapping("/web/selectPictureList")
    @ResponseBody
    public ResponseEntity selectPictureList(){
        ResponseEntity responseData = null;
//        int is_delete = 0;
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("is_delete", is_delete);
        List<Picture> list=pictureDao.selectList(queryWrapper);
        responseData = ResponseEntity.ok();
        responseData.putDataValue("pictureList", list);
        return responseData;
    }

    /**
     * 图片下载
     * @param picture_id
     * @return
     */
    @ApiOperation("图片下载")
    @PostMapping("/web/loaderPictrue")
    @ResponseBody
    public ResponseEntity loaderPicture(HttpServletResponse response,@RequestParam(required = true) Integer picture_id) throws IOException {
        ResponseEntity responseData = null;
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        int is_delete = 0;
        queryWrapper.eq("is_delete", is_delete);
        queryWrapper.eq("picture_id", picture_id);
        Picture picture = pictureDao.selectOne(queryWrapper);
        if (picture != null) {
            String picture_path = picture.getPicture_path();
            String image = picture_path.substring(picture_path.lastIndexOf("/") + 1);
            String newPicture_path = "/www/javaweb/propaganda_system/picture/" + image;
//        response.setHeader("content-type", "application/octet-stream");
//        response.setContentType("application/octet-stream");
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(image, "UTF-8"));
            } catch (UnsupportedEncodingException e2) {
                e2.printStackTrace();
            }
//        FileOutputStream outputStream = new FileOutputStream(new File("图片.jpg"));
            OutputStream outputStream = response.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream(newPicture_path);

            byte[] bytes = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.close();
            fileInputStream.close();
            responseData = ResponseEntity.ok();
            responseData.putDataValue("msg", "下载成功");
            return responseData;
        } else {
            responseData = ResponseEntity.badRequest();
            responseData.putDataValue("msg", "图片不存在无法下载");
            return responseData;
        }
    }

    /**
     * 图片删除
     * @param Authorization
     * @param picture_id
     * @return
     * @throws IOException
     */
    @ApiOperation("图片删除")
    @PostMapping("/web/deletePicture")
    @ResponseBody
    public ResponseEntity deletePicture(@RequestHeader String Authorization, @RequestParam(required = true) Integer picture_id) throws IOException {
        ResponseEntity responseEntity = null;
        String token = Authorization;
        //通过token解密出来的user对象
        User user = JwtToken.unsign(token, User.class);
        //判断token是否存在或过期
        if (flag = myUtil.judgeToken(token)){
            responseEntity = ResponseEntity.forbidden();
            responseEntity.putDataValue("msg","token不存在或已过期");
            return responseEntity;
        }
        if (user.getUser_role()!=2){
            responseEntity = ResponseEntity.badRequest();
            responseEntity.putDataValue("msg","权限错误");
            responseEntity.putDataValue("timestamp",myUtil.getTime());
            return responseEntity;
        }
        int is_delete = 1;
        Picture picture = pictureDao.selectById(picture_id);
        picture.setIs_delete(is_delete);
        pictureDao.updateById(picture);
        responseEntity = ResponseEntity.ok();
        responseEntity.putDataValue("msg", "删除成功");
        return responseEntity;
    }

}
